﻿using System;
using uTinyRipper.Classes;
using uTinyRipper.Classes.TextureImporters;

namespace uTinyRipper.Converters
{
	public static class SpriteConverter
	{
		public static SpriteMetaData GenerateSpriteMetaData(IExportContainer container, SpriteAtlas originAtlas, Sprite origin)
		{
			origin.GetSpriteCoordinatesInAtlas(originAtlas, out Rectf rect, out Vector2f pivot, out Vector4f border);

			SpriteMetaData instance = new SpriteMetaData(container.ExportVersion);
			instance.Name = origin.Name;
			instance.Rect = rect;
			instance.Alignment = SpriteAlignment.Custom;
			instance.Pivot = pivot;
			instance.Border = border;
			if (SpriteMetaData.HasOutline(container.ExportVersion))
			{
				instance.Outline = origin.GenerateOutline(originAtlas, rect, pivot);
			}
			if (SpriteMetaData.HasPhysicsShape(container.ExportVersion))
			{
				if (Sprite.HasPhysicsShape(container.Version))
				{
					instance.PhysicsShape = GetPhysicsShape(container, originAtlas, origin, rect, pivot);
				}
			}
			instance.TessellationDetail = 0;
			if (SpriteMetaData.HasBones(container.ExportVersion))
			{
				if (Sprite.HasBones(container.Version))
				{
					instance.Bones = origin.Bones;
					// NOTE: sprite ID is generated by sprite binary content, but we just generate a random value
					instance.SpriteID = Guid.NewGuid().ToString("N");
#warning TODO:
					/*instance.Vertices = GetBoneVertices(container, origin);
					instance.Indices = GetBoneIndices(container, origin);
					instance.Edges = GetBoneEdges(container, origin);
					instance.Weights = GetBoneWeights(container, origin);*/
				}
			}
			return instance;
		}

		private static Vector2f[][] GetPhysicsShape(IExportContainer container, SpriteAtlas originAtlas, Sprite origin, Rectf rect, Vector2f pivot)
		{
			if (Sprite.HasPhysicsShape(container.Version))
			{
				return origin.GeneratePhysicsShape(originAtlas, rect, pivot);
			}
			return Array.Empty<Vector2f[]>();
		}

		private static int[] GetBoneIndices(IExportContainer container, Sprite origin)
		{
			if (origin.RD.IndexBuffer.Length == 0)
			{
				return Array.Empty<int>();
			}

			int[] indices = new int[origin.RD.IndexBuffer.Length / 2];
			for (int i = 0, j = 0; i < origin.RD.IndexBuffer.Length; i++, j += 2)
			{
				indices[i] = BitConverter.ToUInt16(origin.RD.IndexBuffer, j);
			}
			return indices;
		}
	}
}
